<?php
/**
 * Eren Framework
 * 
 * Cookie Operate Class
 * 
 * @category System
 * @author Manu Soros Leu
 * @copyright manusoros@gmail.com
 */

class Eren_Cookie
{   
    /**
     * Set Cookie Key=>Value
     * 
     * @param string $key
     * @param string $value
     * @param string $region
     * @param int $expireTime
     * @throws Eren_Exception
     */
    public static function set($key, $value, $expireTime = 8100000, $region = '/')
    {
        if(is_array($key) || empty($key)){
            throw new Eren_Exception('The first param of Eren_Cookie::set cant be Array or NULL');
        }
        if(!is_numeric($expireTime)){
            throw new Eren_Exception('The third param of Eren_Cookie::set must be int');
        }
        if(is_array($region) || empty($region)){
            throw new Eren_Exception('The forth param of Eren_Cookie::set cant be Array or NULL');
        }
        $key = (string) $key;
        if(!setcookie($key, $value, time()+$expireTime, $region)){
            throw new Eren_Exception('Set Cookie Error');
        }
    }
    
    /**
     * Get value of the key from Cookie
     * 
     * @param string $key
     * @param string $default
     * @throws Eren_Exception
     * @return string
     */
    public static function get($key, $default = NULL)
    {
        if(is_array($key) || empty($key)){
            throw new Eren_Exception('The first param of Eren_Cookie::get cant be array or null');
        }
        $key = (string) $key;
        if(isset($_COOKIE[$key])){
            return $_COOKIE[$key];
        }
        return $default;
    }
    
    /**
     * Get all values from Cookie
     * 
     * @return array
     */
    public static function getAll()
    {
        return $_COOKIE;
    }
    
    /**
     * Delete Cookie By Key
     * 
     * @param string $key
     * @param string $region
     * @throws Eren_Exception
     */
    public static function delete($key, $region = '/')
    {
        if(is_array($key) || empty($key)){
            throw new Eren_Exception('The first param of Eren_Cookie::delete cant be array or null');
        }
        if(is_array($region) || empty($region)){
            throw new Eren_Exception('The second param of Eren_Cookie::delete cant be Array or NULL');
        }
        $key = (string) $key;
        if(!setcookie($key, '', time()-8100000, $region)){
            throw new Eren_Exception('Delete Cookie Error');
        }   
    }
    
     /**
     * Delete ALL Cookie
     * 
     * @param string $region
     * @throws Eren_Exception
     */
    public static function delAll($region = '/')
    {
        if(is_array($region) || empty($region)){
            throw new Eren_Exception('The param of Eren_Cookie::delAll cant be Array or NULL');
        }
        $all = self::getAll();
        foreach($all as $key=>$value){
            self::delete($key, $region);
        }  
    }
}